package com.example.voicealarm;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import java.util.Calendar;

public class AlarmService extends Service {
    private static final String TAG = "AlarmService";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && "SCHEDULE_ALARM".equals(intent.getAction())) {
            Alarm alarm = intent.getParcelableExtra("alarm");
            if (alarm != null) {
                Log.d(TAG, "Scheduling alarm: " + alarm.ttsText);
                scheduleAlarm(alarm);
            }
        }
        return START_STICKY;
    }

    private void scheduleAlarm(Alarm alarm) {
        // If it's a one-time alarm
        if (!isRepeating(alarm)) {
            scheduleSingleAlarm(alarm);
            return;
        }
        
        // If it's a repeating alarm, schedule for each selected day
        for (int i = 0; i < alarm.activeDays.length; i++) {
            if (alarm.activeDays[i]) {
                scheduleWeeklyAlarm(alarm, i);
            }
        }
    }

    private boolean isRepeating(Alarm alarm) {
        for (boolean day : alarm.activeDays) {
            if (day) return true;
        }
        return false;
    }

    private void scheduleSingleAlarm(Alarm alarm) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, alarm.time.get(Calendar.HOUR_OF_DAY));
        calendar.set(Calendar.MINUTE, alarm.time.get(Calendar.MINUTE));
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        
        // If time has passed, set to tomorrow
        if (calendar.before(Calendar.getInstance())) {
            calendar.add(Calendar.DAY_OF_YEAR, 1);
        }
        
        setAlarm(calendar, alarm);
    }

    private void scheduleWeeklyAlarm(Alarm alarm, int dayOfWeek) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, alarm.time.get(Calendar.HOUR_OF_DAY));
        calendar.set(Calendar.MINUTE, alarm.time.get(Calendar.MINUTE));
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        
        // Set to next occurrence of the selected day (Calendar.DAY_OF_WEEK starts with Sunday=1)
        int currentDay = calendar.get(Calendar.DAY_OF_WEEK) - 1; // Convert to 0-based index
        int targetDay = dayOfWeek; // Already 0-based
        
        // Calculate days until next occurrence
        int daysUntilNext = ((targetDay - currentDay + 7) % 7);
        if (daysUntilNext == 0 && calendar.before(Calendar.getInstance())) {
            // If it's the same day but time has passed, schedule for next week
            daysUntilNext = 7;
        }
        
        calendar.add(Calendar.DAY_OF_YEAR, daysUntilNext);
        
        setAlarm(calendar, alarm);
    }

    private void setAlarm(Calendar calendar, Alarm alarm) {
        Intent intent = new Intent(this, AlarmReceiver.class);
        intent.putExtra("alarm", alarm);
        
        // Use a unique ID for each alarm+day combination to ensure multiple alarms work
        int requestCode = (int) ((alarm.id * 10) + calendar.get(Calendar.DAY_OF_WEEK));
        int flags = PendingIntent.FLAG_UPDATE_CURRENT;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            flags |= PendingIntent.FLAG_IMMUTABLE;
        }
        
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
            this, requestCode, intent, flags);
        
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        if (alarmManager != null) {
            Log.d(TAG, "Setting alarm for " + calendar.getTime() + " with text: " + alarm.ttsText);
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !alarmManager.canScheduleExactAlarms()) {
                Log.e(TAG, "Cannot schedule exact alarms - permission not granted");
                return;
            }
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                alarmManager.setAlarmClock(
                    new AlarmManager.AlarmClockInfo(calendar.getTimeInMillis(), null),
                    pendingIntent
                );
            } else {
                alarmManager.setExact(
                    AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(),
                    pendingIntent
                );
            }
        }
    }
}